﻿using Newtonsoft.Json;
using RabbitMQ.Client;
using System.Text;
using YDT_WebSites.Models;

namespace YDT_WebSites.Services
{
    /// <summary>
    /// 订单发送
    /// </summary>
    public class OrderPublish
    {
        public IModel channel;

        public OrderPublish()
        {
            // 1、建立RabbitMQ连接
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.HostName = "localhost";
            connectionFactory.Port = 5672;
            connectionFactory.UserName = "guest";
            connectionFactory.Password = "guest";
            connectionFactory.VirtualHost = "/";
            IConnection connection = connectionFactory.CreateConnection();

            // 2、创建连接通道
            var channel = connection.CreateModel();
        }

        /// <summary>
        /// 发送商品
        /// </summary>
        public void PublishProduct(Order order)
        {
            //发送商品数据。
            

            // 3、发送商品数据
            // 3.1、创建队列
            channel.QueueDeclare("AddOrder", false, false, false);

            // 3.2、商品转换
            string productJson = JsonConvert.SerializeObject(order);
            byte[] productByte = Encoding.UTF8.GetBytes(productJson);

            // 3.2、发送数据
            channel.BasicPublish("",
                                 "AddOrder",
                                 true,
                                 channel.CreateBasicProperties(),
                                  productByte);
        }
    }
}
